<!--
* description: 总部移库指令发起
* author: duanhy
* createdDate: 2020-11-11
-->
<template>
  <div>
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="false"
      :callback-obj="callbackObj"
    />
    <Batch-Add
      v-if="editBatchVisible"
      :is-dialog-visible="editBatchVisible"
      :dynamic-edit-row-data="editRowData"
      :popups-state="editPopupsState"
      :title-name="titleName"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import apiTransfer from '@/api/apiVeTransferManagement'
import api from '@/api/apiVeData'
import OneTableTemplate from '@/components/templates/oneTable'
import BatchAdd from './batchAdd'
export default {
  name: 'TotalCommand',
  components: {
    OneTableTemplate,
    // Add,
    BatchAdd
  },
  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  // beforeRouteEnter(to, from, next) {
  //   Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'storeRelocation'], function() {
  //     next()
  //   })
  // },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      selectList: [],
      titleName: '',
      dialogShow: false,
      editBatchVisible: false,
      selectionIndex: '',
      selectionVal: [],
      // 网格查询API配置对象
      apiConfig: apiTransfer.listRelocationTotal,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: '',
          size: 'small',
          clickEvent: () => this.batchAdd(),
          text: '新增',
          name: '',
          position: 'left',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          disabled: true,
          clickEvent: () => this.btn('vinSubmit', '1'),
          text: '提交',
          name: '',
          position: 'left',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          disabled: true,
          clickEvent: () => this.btn('vinScrap', '0'),
          text: '作废',
          name: '',
          position: 'left',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey4',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.queryTable(1),
          text: '查询',
          name: 'search',
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          clickEvent: () => this.reset(),
          text: '重置',
          name: 'reset',
          position: 'right'
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              labelName: '移库单：',
              codeField: 'movestockOrderCode',
              isMul: false,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: 'VIN码：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '源仓库：',
              codeField: 'oldHouseId',
              textField: 'oldHouseName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'oldHouseId,oldHouseName',
              type: 'dropdownList',
              isMust: true,
              options: [
                { oldHouseId: '', oldHouseName: '' }
              ]
            },
            {
              compKey: 'compKey4',
              labelName: '目的库：',
              codeField: 'stockId',
              textField: 'stockName',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              oFields: 'stockId,stockName',
              customObj: {
                api: apiTransfer.ListOfWarehouse,
                listQuery: {
                  warehouseId: '4'
                }
              }
            },
            {
              compKey: 'compKey5',
              labelName: '单据状态：',
              codeField: 'auditStatusId',
              textField: 'auditStatusName',
              component: () => import('@/components/org/LookupValue'),
              lookuptype: 'VE1079',
              type: 'dropdownList',
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '制单时间：',
              codeField: 'newDateStart,newDateEnd',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              // dateOptionsType:'3',    //禁用当前日期之前的日期
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '申请时间：',
              codeField: 'applyTimeStart,applyTimeEnd',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey9',
              labelName: '车系：',
              codeField: 'carSeriesId',
              textField: 'carSeriesCn',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'carSeriesId,carSeriesCn',
              customObj: {
                api: api.listOfCarSeries
              }
            },
            {
              compKey: 'compKey10',
              labelName: '基础车型：',
              codeField: 'carConfigId',
              textField: 'carConfigCn',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'carConfigId,carConfigCn',
              parentFileds: 'value:carSeriesId',
              customObj: {
                api: api.queryCarType,
                listQuery: {
                  carSeriesId: ''
                }
              }
            },
            {
              compKey: 'compKey11',
              labelName: '选装包：',
              codeField: 'optionalPagId',
              textField: 'optionalPagName',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'optionalPagId,optionalPagName',
              parentFileds: 'value:carConfigId',
              customObj: {
                api: api.queryCarOptionalPagLinkMessage,
                listQuery: {
                  carConfigId: ''
                }
              }
            },
            {
              compKey: 'compKey12',
              labelName: '车身颜色：',
              codeField: 'carColorId',
              textField: 'carColorName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carColorId,carColorName',
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: api.queryCarColorLinkMessage
              }
            },
            {
              compKey: 'compKey13',
              labelName: '内饰颜色：',
              codeField: 'carIncolorId',
              textField: 'carIncolorName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carIncolorId,carIncolorName',
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: api.queryCarInColorLinkMessage
              }
            }
          ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'movestockOrderCode',
              label: '移库单',
              width: 120
            },
            {
              prop: 'oldHouseName',
              label: '源仓库'
            },
            {
              prop: 'stockName',
              label: '目的库'
            },
            {
              prop: 'auditStatusName',
              label: '单据状态'
            },
            // {
            //   prop: 'auditOpinion',
            //   label: '审核意见'
            // },
            {
              prop: 'vin',
              label: 'VIN',
              width: 160
            },
            {
              prop: 'carSeriesCn',
              label: '车系'
            },
            {
              prop: 'carConfigCn',
              label: '基础车型'
            },
            {
              prop: 'optionalPagName',
              label: '选装包'
            },
            {
              prop: 'carColorName',
              label: '车身颜色'
            },
            {
              prop: 'carIncolorName',
              label: '内饰颜色'
            },
            {
              prop: 'newDate',
              label: '制单时间',
              width: 160
            },
            {
              prop: 'applyMen',
              label: '申请人'
            },
            {
              prop: 'applyTime',
              label: '申请时间',
              width: 160
            },
            {
              prop: 'auditMen',
              label: '审核人'
            },
            {
              prop: 'auditTime',
              label: '审核时间',
              width: 160
            }
          ],
      formField: {
        zb: '1',
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        carColorId: '',
        carIncolorId: '',
        movestockOrderCode: '',
        vin: '',
        oldHouseId: '',
        stockId: '',
        auditStatusId: '',
        newDateStart: '',
        newDateEnd: '',
        applyTimeStart: '',
        applyTimeEnd: '',
        auditTimeStart: '',
        auditTimeEnd: ''
      },
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          if (selection.length === 0) {
            this.tableButtons[1].disabled = true
            this.tableButtons[2].disabled = true
          }
          if (selection !== 0) {
            this.selectList = selection
          }
          this.handleSelectionChange(selection)
        }
      },
      // 是否使用刷新Key的方式刷新弹窗
      resetDialogKey: false,
      isShowChooes: false
    }
  },
  mounted() {
    // 列表查询
    const that = this
    this.queryTable(1)
    setTimeout(() => {
      // that.dlrId = that.$refs['multipleTable'].list[0].dlrId
      that.init()
    }, 2000)
  },
  methods: {
    // 设置表格选择框 是否禁用
    getSelectable(row, index) {
      if (row.auditStatusId === '1') {
        return true
      }
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },
    close(type) {
      if (type === 1) {
        this.queryTable(1)
      }
      this.dialogShow = false
      this.editBatchVisible = false
    },
    // 单条删除
    oneDelete(index) {
      const data = [this.$refs['multipleTable'].list[index]]
      this.delData(data, index)
    },
    // 批量删除
    batchDelete() {
      const data = this.$refs['multipleTable'].$refs['multipleTable'].selection
      this.delData(data)
    },
    // 删除
    delData(selectData) {
      if (selectData.length === 0) {
        this.$confirm('请选中需要作废的项', '提示')
      } else {
        const that = this
        this.$confirm('确定要作废吗?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const arr = that.$refs['multipleTable'].list
          selectData.forEach(e => {
            for (let i = arr.length - 1; i >= 0; i--) {
              if (arr.length > 0 && arr[i].index === e.index) {
                arr.splice(i, 1)
              }
            }
          })
        }).catch(() => {})
      }
    },
    // 新增
    batchAdd() {
      this.titleName = '总部移库指令新增'
      this.editRowData = { api: apiTransfer.listStockCar }
      this.editBatchVisible = true
    },
    // 判断数组是否含有重复元素
    isRepeat(arr) {
      var hash = {}
      for (var i in arr) {
        if (hash[arr[i]]) {
          return true
        }
        // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
        hash[arr[i]] = true
      }
      return false
    },
    // 提交===1，报废===0
    btn(type, num) {
      var dataForm = {}
      dataForm[type] = num
      const obj = {
        vinlist: [],
        uList: [],
        list: []
      }
      for (const k in this.selectList) {
        obj.vinlist.push(this.selectList[k].vin)
        obj.uList.push({
          vin: this.selectList[k].vin,
          updateControlId: this.selectList[k].updateControlId,
          movestockOrderCode: this.selectList[k].movestockOrderCode
        })
        obj.list.push({
          carHouseManager: this.selectList[k].warehouseEmpName,
          warehouseEmpName: this.selectList[k].warehouseEmpName,
          outOrderNo: this.selectList[k].outStoreId,
          movestockOrderId: this.selectList[k].movestockOrderId,
          dlrId: this.selectList[k].dlrId,
          vin: this.selectList[k].vin,
          oldPlaceId: this.selectList[k].oldPlaceId,
          oldAreaId: this.selectList[k].oldAreaId,
          oldHouseId: this.selectList[k].oldHouseId,
          movestockOrderCode: this.selectList[k].movestockOrderCode,
          receiveGarageAddress: this.selectList[k].receiveGarageAddress,
          remark: this.selectList[k].remark
        })
      }
      if (this.isRepeat(obj.vinlist) && type !== 'vinScrap') {
        this.$message({ message: '同一辆车不可提交多条移库申请', type: 'warn', uration: 2000 })
        return false
      }
      delete obj.vinlist
      dataForm = { ...obj, ...dataForm }
      this.$refs['multipleTable'].listLoading = true
      this.$requestAPI(this.$getParams({
        apiConfig: apiTransfer.updateTransferSubmit,
        variables: dataForm
      })).then(response => {
        this.$refs['multipleTable'].listLoading = false
        if (response.result === '0') {
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', uration: 2000 })
          }
          return
        }
        this.$message({ message: response.msg, type: 'warn', uration: 2000 })
        this.queryTable(1)
        dataForm = {}
      }).catch(err => {
        this.$refs['multipleTable'].listLoading = false
        console.info(err)
      })
    },
    editDelete(index) {
      this.$refs['multipleTable'].list.splice(index, 1)
    },

    // 保存传值过来
    save(formField) {
      if (formField.index !== '') {
        this.$refs['multipleTable'].list[formField.index] = formField
      } else {
        this.$refs['multipleTable'].list.push(formField)
      }
      // console.log(formField)
      // this.close()
    },
    // 获取门店id
    init() {
      const newSelect = []
      this.$requestAPI(this.$getParams({
        apiConfig: apiTransfer.ListOfWarehouse,
        variables: {
          isEnable: '1',
          pageIndex: 1,
          pageSize: 500,
          warehouseId: '3'
        }
      })).then(response => {
        if (response.result === '0') {
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', uration: 2000 })
          }
          return
        }
        for (const k in response.rows) {
          newSelect.push({
            oldHouseId: response.rows[k].stockId,
            oldHouseName: response.rows[k].stockName
          })
        }
        for (const k in this.tableComponents) {
          if (this.tableComponents[k].codeField === 'oldHouseId') {
            this.tableComponents[k].options = newSelect
            return false
          }
        }
      }).catch(err => {
        console.info(err)
      })
    }
  }
}
</script>
